//
//  ViewController.m
//  pacc
//
//  Created by 测试 on 2018/5/15.
//  Copyright © 2018年 测试. All rights reserved.
//

#import "ViewController.h"
#import <CoreData/CoreData.h>
#import "Person+CoreDataClass.h"
#import "Hospital+CoreDataClass.h"
#import "SlideBarCell.h"
#import "searchController.h"
#import "pingtairenwuModel.h"
#import "ZZcommonModel.h"
#import "orderModel.h"
#import "taskDetailsCVc.h"
#import "yuepianController.h"
#import "woderenwuModel.h"
#import "HotelCalendarViewController.h"
#import <FSCalendar.h>
#import "RangePickerViewController.h"
#import "shenhetuihuiController.h"
#define TOPHEIGHT 45

@interface ViewController ()<UITableViewDelegate,UITableViewDataSource,NSFetchedResultsControllerDelegate,FSCalendarDataSource,FSCalendarDelegate>
@property (nonatomic, strong) NSManagedObjectContext *companyMOC;
@property (strong, nonatomic)  UITableView *myTableView1;
@property (strong, nonatomic)  UITableView *myTableView2;
@property (strong, nonatomic)  UITableView *myTableView;
@property (strong, nonatomic)  UIImageView *myImageView;
@property (weak , nonatomic) FSCalendar *calendar;
@property (nonatomic, strong) UIView *maskLayer;

@property(nonatomic,copy)NSString * startStr;
@property(nonatomic,copy)NSString * endStr;

@property(nonatomic,assign)BOOL dateSearch;
@property (strong, nonatomic) NSFetchedResultsController *fetchedResultController;
//创建一个管理者，并且通过属性强引用，使其不会被释放
///@brife TableViews的数据源
@property (strong, nonatomic) NSMutableArray *dataSource;
@property (strong, nonatomic) NSMutableArray *dataSource1;
@property (strong, nonatomic) NSMutableArray *dataSource2;
@property (strong, nonatomic) NSMutableArray *dataSource3;
@property (strong, nonatomic) NSMutableArray *dataSource4;
@property (strong, nonatomic) NSMutableArray *dataSource5;
@property (strong, nonatomic) NSMutableArray *dataSource6;
@property (strong, nonatomic) NSMutableArray *temdataSource;

@property (copy, nonatomic) NSString *nameStr;
@property (assign) NSInteger tabCount;
@property (assign) BOOL isFrash;
@property (assign) int pageNo1;
@property (assign) int pageNo2;
@property (assign) int pageNo3;
@property (assign) int pageNo4;
@property (assign) int pageNo5;
@property (assign) int pageNo6;
@property(nonatomic,copy)NSString * sum;

@property(nonatomic,strong) UILabel *startDateLabel;
@property(nonatomic,strong) UILabel *endDateLabel;
@property(nonatomic,strong) UILabel *numLabel;

@property (strong, nonatomic) NSMutableArray *btnNameArr;

///@brife 整个视图的大小
@property (assign) CGRect mViewFrame;

///@brife 下方的ScrollView
@property (strong, nonatomic) UIScrollView *scrollView;

///@brife 上方的按钮数组
@property (strong, nonatomic) NSMutableArray *topViews;

///@brife 下方的表格数组
@property (strong, nonatomic) NSMutableArray *scrollTableViews;


///@brife 当前选中页数
@property (assign) NSInteger currentPage;

///@brife 下面滑动的View
@property (strong, nonatomic) UIView *slideView;

///@brife 上方的view
@property (strong, nonatomic) UIView *topMainView;

///@brife 上方的ScrollView
@property (strong, nonatomic) UIScrollView *topScrollView;

@end

@implementation ViewController
@synthesize maskLayer;
#pragma mark - ----- Create CoreData Context ------

/**
 创建上下文对象
 */
- (NSManagedObjectContext *)contextWithModelName2:(NSString *)modelName {
    // 创建上下文对象，并发队列设置为主队列
    NSManagedObjectContext *context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    
    // 创建托管对象模型，并使用Company.momd路径当做初始化参数
    NSURL *modelPath = [[NSBundle mainBundle] URLForResource:modelName withExtension:@"momd"];
    NSManagedObjectModel *model = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelPath];
    
    // 创建持久化存储调度器
    NSPersistentStoreCoordinator *coordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
    
    // 创建并关联SQLite数据库文件，如果已经存在则不会重复创建
    NSString *dataPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
    dataPath = [dataPath stringByAppendingFormat:@"/%@.sqlite", modelName];
    [coordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:dataPath] options:nil error:nil];
    
    // 上下文对象设置属性为持久化存储器

    context.persistentStoreCoordinator = coordinator;
    
    return context;
}
#pragma mark - ----- Create CoreData Context ------

/**
 创建上下文对象
 */
- (NSManagedObjectContext *)contextWithModelName:(NSString *)modelName {
    // 创建上下文对象，并发队列设置为主队列
    NSManagedObjectContext *context = [[NSManagedObjectContext alloc] initWithConcurrencyType:NSMainQueueConcurrencyType];
    
    // 创建托管对象模型，并使用Company.momd路径当做初始化参数
    NSURL *modelPath = [[NSBundle mainBundle] URLForResource:modelName withExtension:@"momd"];
    NSManagedObjectModel *model = [[NSManagedObjectModel alloc] initWithContentsOfURL:modelPath];
    
    // 创建持久化存储调度器
    NSPersistentStoreCoordinator *coordinator = [[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:model];
    
    // 创建并关联SQLite数据库文件，如果已经存在则不会重复创建
    NSString *dataPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject;
    dataPath = [dataPath stringByAppendingFormat:@"/%@.sqlite", modelName];
    [coordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:[NSURL fileURLWithPath:dataPath] options:nil error:nil];
    
    // 上下文对象设置属性为持久化存储器
    context.persistentStoreCoordinator = coordinator;
    
    return context;
}
- (NSManagedObjectContext *)companyMOC {
    if (!_companyMOC) {
        _companyMOC = [self contextWithModelName:@"Model"];
    }
    return _companyMOC;
}
#pragma mark - ----- NSFetchedResultsController ------

- (IBAction)refreshView:(UIButton *)sender {
    // 创建请求对象，并指明操作User表
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Person"];
    
    // 设置排序规则，指明根据age字段升序排序
    NSSortDescriptor *heightSort = [NSSortDescriptor sortDescriptorWithKey:@"height" ascending:YES];
    request.sortDescriptors = @[heightSort];
    
    // 创建NSFetchedResultsController控制器实例，并绑定MOC
    NSError *error = nil;
    self.fetchedResultController = [[NSFetchedResultsController alloc] initWithFetchRequest:request
                                                                       managedObjectContext:self.companyMOC
                                                                         sectionNameKeyPath:@"sectionName"
                                                                                  cacheName:nil];
    // 设置代理，并遵守协议
    self.fetchedResultController.delegate = self;
    // 执行获取请求，执行后FRC会从持久化存储区加载数据，其他地方可以通过FRC获取数据
    [self.fetchedResultController performFetch:&error];
    
    // 错误处理
    if (error) {
        NSLog(@"NSFetchedResultsController init error : %@", error);
    }
    
    // 刷新UI
    [self.myTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"identifier"];
    [self.myTableView reloadData];
}

// 这里是简单模拟UI删除cell后，本地持久化区数据和UI同步的操作。在调用下面MOC保存上下文方法后，FRC会回调代理方法并更新UI
//- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
//    
//    if (editingStyle == UITableViewCellEditingStyleDelete) {
//        // 删除托管对象
//        Person *person = [self.fetchedResultController objectAtIndexPath:indexPath];
//        [self.companyMOC deleteObject:person];
//        
//        // 保存上下文环境，并做错误处理
//        NSError *error = nil;
//        if (![self.companyMOC save:&error]) {
//            NSLog(@"tableView delete cell error : %@", error);
//        }
//    }
//}

#pragma mark - ----- NSFetchedResultsControllerDelegate ------

// Cell数据源发生改变会回调此方法，例如添加新的托管对象等
- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(nullable NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(nullable NSIndexPath *)newIndexPath {
    
    switch (type) {
        case NSFetchedResultsChangeInsert:
            [self.myTableView insertRowsAtIndexPaths:@[newIndexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
            break;
        case NSFetchedResultsChangeDelete:
            [self.myTableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
            break;
        case NSFetchedResultsChangeMove:
            [self.myTableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
            [self.myTableView insertRowsAtIndexPaths:@[newIndexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
            break;
        case NSFetchedResultsChangeUpdate: {
            Person *person = [self.fetchedResultController objectAtIndexPath:indexPath];
            
            UITableViewCell *cell = [self.myTableView cellForRowAtIndexPath:indexPath];
            cell.textLabel.text = person.name;
            [self.myTableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
        }
            break;
    }
}

// Section数据源发生改变回调此方法，例如修改section title等
- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type {
    
    switch (type) {
        case NSFetchedResultsChangeInsert:
            [self.myTableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationAutomatic];
            break;
        case NSFetchedResultsChangeDelete:
            [self.myTableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationAutomatic];
            break;
        default:
            break;
    }
}

// 本地数据源发生改变，将要开始回调FRC代理方法。
- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller {
    [self.myTableView beginUpdates];
}

// 本地数据源发生改变，FRC代理方法回调完成。
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
    [self.myTableView endUpdates];
}

// 返回section的title，可以在这里对title做进一步处理。这里修改title后，对应section的indexTitle属性会被更新。
- (nullable NSString *)controller:(NSFetchedResultsController *)controller sectionIndexTitleForSectionName:(NSString *)sectionName {
    return [NSString stringWithFormat:@"sectionName %@", sectionName];
}

#pragma mark - ----- 生成测试数据 ------

- (IBAction)createTestData:(UIButton *)sender {
    for (int i = 0; i < 5; i++) {
        Person *person    = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:self.companyMOC];
        person.name    = [NSString stringWithFormat:@"lxz %d", i];
        person.height         = i + 15;
        person.sectionName = [NSString stringWithFormat:@"%d", i % 5];
    }
    
    NSError *error = nil;
    if (self.companyMOC.hasChanges) {
        [self.companyMOC save:&error];
    }
}
#pragma mark - ----- CRUD ------

/**
 添加Student实例
 */
- (IBAction)schoolAdd:(UIButton *)sender {
    // 创建托管对象，并指明创建的托管对象所属实体名
    Person *person = [NSEntityDescription insertNewObjectForEntityForName:@"Person" inManagedObjectContext:self.companyMOC];
    person.name = @"lxz";
    // 实体中所有基础数据类型，创建类文件后默认都是NSNumber类型的
    person.age = 23;
    person.sectionName = @"7";

    // 通过上下文保存对象，并在保存前判断是否有更改
    NSError *error = nil;
    if (self.companyMOC.hasChanges) {
        [self.companyMOC save:&error];
    }
    
    // 错误处理，可以在这实现自己的错误处理逻辑
    if (error) {
        NSLog(@"CoreData Insert Data Error : %@", error);
    }
}
/**
 查找Student实例
 */
- (IBAction)schoolSearch:(UIButton *)sender {
    // 建立获取数据的请求对象，指明操作的实体为Student
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"Person"];
    
    // 执行获取操作，获取所有Student托管对象
    NSError *error = nil;
    NSArray<Person *> *persons = [self.companyMOC executeFetchRequest:request error:&error];
    
    // 遍历输出查询结果
    [persons enumerateObjectsUsingBlock:^(Person * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        NSLog(@"Student Name : %@, height : %f,sectionName : %@", obj.name, obj.height,obj.sectionName);
    }];
    
    // 错误处理
    if (error) {
        NSLog(@"CoreData Ergodic Data Error : %@", error);
    }
}
/**
#pragma mark --tableView delegate--

// 通过FRC的sections数组属性，获取所有section的count值，将其设置为section number
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.fetchedResultController.sections.count;
}

// 通过当前section的下标从sections数组中取出对应的section对象，并从section对象中获取所有对象count，将其设置为row number
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.fetchedResultController.sections[section].numberOfObjects;
}

// FRC根据indexPath获取托管对象，并给cell赋值
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    Person *person = [self.fetchedResultController objectAtIndexPath:indexPath];
    
    UITableViewCell *cell     = [tableView dequeueReusableCellWithIdentifier:@"identifier" forIndexPath:indexPath];
    cell.textLabel.text       = person.name;
    cell.detailTextLabel.text = [NSString stringWithFormat:@"%lld", person.height];
    return cell;
}
// 创建FRC对象时，通过sectionNameKeyPath:传递进去的section title的属性名，在这里获取对应的属性值
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    return self.fetchedResultController.sections[section].indexTitle;
}

// 是否可以编辑
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

**/
#pragma mark -- 初始化表格的数据源
-(void) initDataSource{
    _dataSource = [[NSMutableArray alloc] initWithCapacity:_tabCount];
    
    for (int i = 1; i <= _tabCount; i ++) {
        
        NSMutableArray *tempArray  = [[NSMutableArray alloc] initWithCapacity:5];
        
        for (int j = 1; j <= 9; j ++) {
            
            NSString *tempStr = [NSString stringWithFormat:@"我是第%d个TableView的第%d条数据。", i, j];
            [tempArray addObject:tempStr];
        }
        
        [_dataSource addObject:tempArray];
    }
}


#pragma mark -- 实例化ScrollView
-(void) initScrollView{
    _scrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, self.view.frame.origin.y, self.view.frame.size.width, self.view.frame.size.height - TOPHEIGHT)];
    _scrollView.delegate = self;
    _scrollView.contentSize = CGSizeMake(self.view.frame.size.width * _tabCount, 0);
    _scrollView.backgroundColor = baseBackgroundColor;
    self.scrollView.alwaysBounceVertical = NO;
    _scrollView.pagingEnabled = YES;
    _scrollView.bounces = NO;
    [self.view addSubview:_scrollView];
}

#pragma mark -- 实例化顶部的tab
-(void) initTopTabs{
    
    if (!_btnNameArr) {
        _btnNameArr = [[NSMutableArray alloc]initWithCapacity:_tabCount];
    }
    
    CGFloat width = _mViewFrame.size.width / 6;
    
    if(self.tabCount <=6){
        width = _mViewFrame.size.width / self.tabCount;
    }
    
    _topMainView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, _mViewFrame.size.width, TOPHEIGHT)];
    
    _topScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, _mViewFrame.size.width, TOPHEIGHT)];
    
    _topScrollView.showsHorizontalScrollIndicator = NO;
    
    _topScrollView.showsVerticalScrollIndicator = YES;
    
    _topScrollView.bounces = NO;
    
    _topScrollView.delegate = self;
    
    if (_tabCount >= 6) {
        _topScrollView.contentSize = CGSizeMake(width * _tabCount, TOPHEIGHT);
        
    } else {
        _topScrollView.contentSize = CGSizeMake(_mViewFrame.size.width, TOPHEIGHT);
    }
    
    
    [self.view addSubview:_topMainView];
    
    [_topMainView addSubview:_topScrollView];
    
    
    
    for (int i = 0; i < _btnNameArr.count; i ++) {
        
        UIView *view = [[UIView alloc] initWithFrame:CGRectMake(i * width, 0, width, TOPHEIGHT)];
        
        view.backgroundColor = [UIColor whiteColor];
        
//        if (i % 2) {
//            //            view.backgroundColor = [UIColor grayColor];
//        }
        
        UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, width, TOPHEIGHT)];
        button.tag = i;
        [button setTitle:[NSString stringWithFormat:@"%@", _btnNameArr[i]] forState:UIControlStateNormal];
        [button setTitleColor:basetextColor forState:UIControlStateNormal];
        [button addTarget:self action:@selector(tabButton:) forControlEvents:UIControlEventTouchUpInside];
        button.titleLabel.font = textfont;
        [view addSubview:button];
        
        UIView *vview = [[UIView alloc] initWithFrame:CGRectMake(width-1,ZTmargin*2, 1,TOPHEIGHT-ZTmargin*4)];
        [button addSubview:vview];
        vview.backgroundColor = ZXColor(208, 208, 208);
        
        [_topViews addObject:view];
        [_topScrollView addSubview:view];
    }
}
#pragma mark --点击顶部的按钮所触发的方法
-(void) tabButton: (id) sender{
    UIButton *button = sender;
    [_scrollView setContentOffset:CGPointMake(button.tag * _mViewFrame.size.width, 0) animated:YES];
}

#pragma mark --初始化下方的TableViews
-(void) initDownTables{
    for (int i = 0; i < 2; i ++) {
        UITableView * myTableView = [[UITableView alloc] initWithFrame:CGRectMake(i * _mViewFrame.size.width, ZTmargin + TOPHEIGHT, _mViewFrame.size.width, _mViewFrame.size.height - TOPHEIGHT-64-50)];
        myTableView.backgroundColor = baseBackgroundColor;
        myTableView.delegate = self;
        myTableView.dataSource = self;
        myTableView.tag = i;
        switch (i) {
            case 0:
                _myTableView1 = myTableView;
                break;
            case 1:
                _myTableView2 = myTableView;
                break;
            default:
                break;
        }
        myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_scrollTableViews addObject:myTableView];
        [_scrollView addSubview:myTableView];
    }
}

#pragma mark -- 初始化滑动的指示View
-(void) initSlideView{
    
    CGFloat width = _mViewFrame.size.width / 6;
    
    if(self.tabCount <=6){
        width = _mViewFrame.size.width / self.tabCount;
    }
    
    _slideView = [[UIView alloc] initWithFrame:CGRectMake(0, TOPHEIGHT - 1, width, 1)];
    [_slideView setBackgroundColor:titleBlueColor];
    [_topScrollView addSubview:_slideView];
}

#pragma mark --根据scrollView的滚动位置复用tableView，减少内存开支
-(void) updateTableWithPageNumber: (NSUInteger) pageNumber{
//    [self changeData];
    [self changeBackColorWithPage:pageNumber];
    CGRect tableNewFrame = CGRectMake(pageNumber * _mViewFrame.size.width, TOPHEIGHT, _mViewFrame.size.width, _mViewFrame.size.height - TOPHEIGHT-64-50);
    int tabviewTag = pageNumber % 2;
    UITableView *reuseTableView = _scrollTableViews[tabviewTag];
    reuseTableView.frame = tableNewFrame;
    NSLog(@"切换tableView数据");
    [reuseTableView reloadData];
    [self loadData];
}


- (void) changeBackColorWithPage: (NSInteger) currentPage {
    for (int i = 0; i < _btnNameArr.count; i ++) {
        UIView *tempView = _topViews[i];
        UIButton *button = [tempView subviews][0];
        if (i == currentPage) {
            tempView.backgroundColor = [UIColor whiteColor];
            [button setTitleColor:titleBlueColor forState:UIControlStateNormal];
        } else {
            tempView.backgroundColor = [UIColor whiteColor];
            [button setTitleColor:baseGlayColor forState:UIControlStateNormal];
        }
    }
    [self.view setNeedsLayout];
}


#pragma mark -- scrollView的代理方法

-(void) modifyTopScrollViewPositiong: (UIScrollView *) scrollView{
    if ([_topScrollView isEqual:scrollView]) {
        CGFloat contentOffsetX = _topScrollView.contentOffset.x;
        
        CGFloat width = _slideView.frame.size.width;
        
        int count = (int)contentOffsetX/(int)width;
        
        CGFloat step = (int)contentOffsetX%(int)width;
        
        CGFloat sumStep = width * count;
        
        if (step > width/2) {
            
            sumStep = width * (count + 1);
            
        }
        
        [_topScrollView setContentOffset:CGPointMake(sumStep, 0) animated:YES];
        
        
        return;
    }
    
}

///拖拽后调用的方法
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    //[self modifyTopScrollViewPositiong:scrollView];
}



-(void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView{
    [self scrollViewDidEndDecelerating:scrollView];
    
    
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView

{
    if ([scrollView isEqual:_scrollView]) {
        _currentPage = _scrollView.contentOffset.x/_mViewFrame.size.width;
        

        //    UITableView *currentTable = _scrollTableViews[_currentPage];
        //    [currentTable reloadData];
        
        [self updateTableWithPageNumber:_currentPage];
        NSLog(@"scrollView的页数=%ld",(long)_currentPage);
        
        [self changeBackColorWithPage:_currentPage];
        
        return;
    }
    [self modifyTopScrollViewPositiong:scrollView];
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if ([_scrollView isEqual:scrollView]) {
        CGRect frame = _slideView.frame;
        
        if (self.tabCount <= 6) {
            frame.origin.x = scrollView.contentOffset.x/_tabCount;
        } else {
            frame.origin.x = scrollView.contentOffset.x/6;
            
        }
        
        _slideView.frame = frame;
    }
    
}


-(void)yuepian:(UIButton*)sender{
    if (!my_AppDelegate.grabO) {
        return;
    }
    yuepianController *vc = [yuepianController new];
    NSString * zid = [sender titleForState:UIControlStateHighlighted];
//    vc.zid = zid;
    if (!zid) {
        [SVProgressHUD showErrorWithStatus:@"暂无图片"];
    }else{
        vc.yuepianURL = zid;
        [self.navigationController pushViewController:vc animated:YES];
    }
}


#pragma mark -- talbeView的代理方法
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
//    NSMutableArray *tempArray = _dataSource[_currentPage];
//    NSLog(@"tempArray.count = %lu",(unsigned long)_dataSource.count);
//    return 10;
    return _dataSource.count;
}

-(CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 110;
}

-(UITableViewCell *)tableView:tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    BOOL nibsRegistered=NO;
    if (!nibsRegistered) {
        UINib *nib=[UINib nibWithNibName:@"SlideBarCell" bundle:nil];
        [tableView registerNib:nib forCellReuseIdentifier:@"SlideBarCell"];
        nibsRegistered=YES;
    }
    
    
    SlideBarCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SlideBarCell"];
    cell.arrData = _dataSource[indexPath.row];
    [cell.yuepianBtn setTitle:cell.pacUrl forState:UIControlStateHighlighted];
    [cell.yuepianBtn addTarget:self action:@selector(yuepian:) forControlEvents:UIControlEventTouchUpInside];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
  
//    NSLog(@"%@",cell.tipTitle.text);
    return cell;
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath{
    SlideBarCell*displayCell = (SlideBarCell *)cell;

    if (_currentPage == 5) {
        displayCell.typeBtn.hidden = NO;
        displayCell.gongdanNameConstraint.constant = 60;
        int odrStatus = [displayCell.odrStatus intValue];
        NSLog(@"odrStatus=%d",odrStatus);
        [displayCell.typeBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        switch (odrStatus) {
            case 2:
                [displayCell.typeBtn setTitle:@" 已接单 " forState:UIControlStateNormal];
                [displayCell.typeBtn setBackgroundColor:RGB(207, 106, 41)];
                break;
            case 3:
                [displayCell.typeBtn setTitle:@" 已完工 " forState:UIControlStateNormal];
                
                [displayCell.typeBtn setBackgroundColor:RGB(77, 178, 220)];
                break;
            case 4:
                [displayCell.typeBtn setTitle:@" 已审核 " forState:UIControlStateNormal];
                
                [displayCell.typeBtn setBackgroundColor:RGB(91, 187, 59)];
                break;
            case 5:
                [displayCell.typeBtn setTitle:@" 未通过 " forState:UIControlStateNormal];
                
                [displayCell.typeBtn setBackgroundColor:RGB(211, 73, 66)];
                break;
            case 6:
                [displayCell.typeBtn setTitle:@" 已付款 " forState:UIControlStateNormal];
                
                [displayCell.typeBtn setBackgroundColor:RGB(73, 130, 232)];
                break;
            case 7:
                [displayCell.typeBtn setTitle:@" 已取消 " forState:UIControlStateNormal];
                
                [displayCell.typeBtn setBackgroundColor:RGB(88, 88, 88)];
                break;
            default:
                break;
        }
    }else {
        displayCell.gongdanNameConstraint.constant = 8;
        displayCell.typeBtn.hidden = YES;
    }
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (!my_AppDelegate.grabO) {
        return;
    }
    _isFrash = NO;
    SlideBarCell * cell =[tableView cellForRowAtIndexPath:indexPath];
    if ([cell.odrStatus intValue]==5) {
        shenhetuihuiController *vc = [shenhetuihuiController new];
        vc.type = _currentPage;
        vc.zid = cell.zid;
        vc.yuepianURL = cell.pacUrl;
        vc.odrStatus = @"未通过";
        [self.navigationController pushViewController:vc animated:YES];
    }else{
        taskDetailsCVc *vc =[taskDetailsCVc new];
        vc.type = _currentPage;
        vc.zid = cell.zid;
        vc.yuepianURL = cell.pacUrl;
        NSString * nameStr;
        switch ([cell.odrStatus intValue]) {
            case 1:
                nameStr = @"已下单";
                break;
            case 2:
                nameStr = @"已接单";
                
                break;
            case 3:
                nameStr = @"已完工";
                
                break;
            case 4:
                nameStr = @"已审核";
                
                break;
            case 5:
                nameStr = @"未通过";
                
                break;
            case 6:
                nameStr = @"已付款";
                break;
                
            default:
                break;
        }
        vc.odrStatus = nameStr;
        vc.returnValueBlock = ^(BOOL passedValue){
            self.isFrash = passedValue;
        };
        _isFrash = YES;
        [self.navigationController pushViewController:vc animated:YES];
    }
    NSLog(@"点击cell");
}
#pragma mark---------
- (void)viewDidLoad {
    [super viewDidLoad];
    _btnNameArr = [NSMutableArray arrayWithObjects:@"已接单",@"已完工",@"已审核",@"未通过",@"已付款",@"全部", nil];
    _scrollTableViews = [[NSMutableArray alloc] init];
    _tabCount = _btnNameArr.count;
    _mViewFrame = self.view.frame;
    if (!_topViews) {
        _topViews =[[NSMutableArray alloc]init];
    }
    _pageNo1 =_pageNo2 =_pageNo3 =_pageNo4 =_pageNo5 =_pageNo6 = 1;
//    [self initDataSource];
    
    [self initScrollView];
    
    [self initTopTabs];
    
    [self initDownTables];
    
    [self loadData];

    [self refersh];
    
    [self creatNavRightBtn];
    
    [self initSlideView];

    [self changeBackColorWithPage:0];
    
    
    _myImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"kong"]];
    _myImageView.frame = CGRectMake((ScreenWidth-134)/2, 100, 134, 134);
    [self.view addSubview:_myImageView];
    _myImageView.hidden = YES;
    
    if (!my_AppDelegate.grabO) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"温馨提示"message:@"您的账号正在审核中，目前没有接单和阅片权限，我们将在1个工作日内完成审核，谢谢" preferredStyle:UIAlertControllerStyleAlert];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            NSLog(@"order/chooseDoctor");
        }];
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"抢单" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
          
            
          
        }];
        
        [alertController addAction:okAction];
//        [alertController addAction:cancelAction];
        [self presentViewController:alertController animated:YES completion:nil];

    }
    
   
    FSCalendar *calendar = [[FSCalendar alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 300)];
    calendar.backgroundColor = [UIColor whiteColor];
    calendar.dataSource = self;
    calendar.delegate = self;
    [self.view addSubview:calendar];
    self.calendar = calendar;
    NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];//设置为中文
    _calendar.locale = locale;
    _calendar.hidden = YES;
    calendar.allowsMultipleSelection = YES;
    
}
- (void)action_removeMask{
    // 移除全屏点击事件
    [maskLayer removeFromSuperview];
}
- (void)addMaskLayer{
    
    // 添加遮罩
    maskLayer = [UIView  new];
    [maskLayer setFrame:[[UIScreen mainScreen] bounds]];
    [maskLayer setBackgroundColor:[UIColor colorWithRed:0 green:0 blue:0 alpha:0.3]];
    [self.view addSubview:maskLayer];
}

-(void)refersh{
    _pageNo1 =_pageNo2 =_pageNo3 =_pageNo4 =_pageNo5 =_pageNo6 = 1;
    _myTableView1.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        NSLog(@"刷新");
        [self loadData];
    }];
    _myTableView2.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        NSLog(@"刷新");
        [self loadData];
    }];
    _myTableView1.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self loadMoreData];
    }];
    _myTableView2.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        [self loadMoreData];
    }];
}
-(void)viewDidAppear:(BOOL)animated{
    if (_dateSearch) {
//        [self loadData4];
    }
}
-(void)viewWillAppear:(BOOL)animated{
    [self loadData];
    if (my_AppDelegate.fromMessage) {
        UIButton * button = [[UIButton alloc]init];
        button.tag = 1;
        _currentPage = 1;
        [self tabButton:button];
    }
}
-(void)viewWillDisappear:(BOOL)animated{
    my_AppDelegate.fromMessage = NO;
    [_myTableView1.mj_header endRefreshing];
    [_myTableView2.mj_header endRefreshing];
    [_myTableView1.mj_footer endRefreshing];
    [_myTableView2.mj_footer endRefreshing];
}
-(void)loadMoreData{
    NSMutableDictionary *dic =[NSMutableDictionary dictionary];
    _pageNo1++;
    _pageNo2++;
    _pageNo3++;
    _pageNo4++;
    _pageNo5++;
    _pageNo6++;

    switch (_currentPage) {
        case 0:
            //已接单
            [dic setValue:[NSString stringWithFormat:@"%d",_pageNo1] forKey:@"page"];

            [dic setValue:@2 forKey:@"status"];
            _nameStr =@"已接单";
            
            break;
        case 1:
            //已接单
            [dic setValue:[NSString stringWithFormat:@"%d",_pageNo2] forKey:@"page"];

            [dic setValue:@3 forKey:@"status"];
            _nameStr =@"已完工";
            break;
        case 2:
            //已接单
            [dic setValue:[NSString stringWithFormat:@"%d",_pageNo3] forKey:@"page"];

            [dic setValue:@4 forKey:@"status"];
            _nameStr =@"已审核";
            break;
        case 3:
            //已接单
            [dic setValue:[NSString stringWithFormat:@"%d",_pageNo4] forKey:@"page"];

            [dic setValue:@5 forKey:@"status"];
            _nameStr =@"未通过";
            break;
        case 4:
            //已接单
            [dic setValue:[NSString stringWithFormat:@"%d",_pageNo5] forKey:@"page"];

            [dic setValue:@6 forKey:@"status"];
            _nameStr =@"已付款";
            break;
        case 5:
            //已接单
            //            [dic setValue:@2 forKey:@"status"];
            [dic setValue:[NSString stringWithFormat:@"%d",_pageNo6] forKey:@"page"];

            _nameStr =@"全部";
            break;
        default:
            break;
    }
    NSLog(@"_dataSource1==%@",self->_dataSource1);
    NSLog(@"_dataSource2==%@",self->_dataSource2);

    [dic setValue:@10 forKey:@"size"];
    [dic setValue:my_AppDelegate.token forKey:@"token"];
     
    [self.temdataSource removeAllObjects];
    self.myTableView1.scrollEnabled = NO;
    self.myTableView2.scrollEnabled = NO;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.myTableView1.scrollEnabled = YES;
        self.myTableView2.scrollEnabled = YES;
    });
    [NetWorking startPOSTRequestWithUrl:@"ordergetDoctorOrder" parameters:dic logMes:_nameStr show:NO success:^(NSDictionary *data) {
        self.myTableView1.scrollEnabled = YES;
        self.myTableView2.scrollEnabled = YES;
        NSArray *arr = [data objectForKey:@"data"];
        switch (self->_currentPage) {
            case 0:
                //已接单
                if (arr&&![arr isEqual:[NSNull null]]) {
                    for (NSDictionary * dic in arr) {
                        woderenwuModel * model = [woderenwuModel new];
                        [model setValuesForKeysWithDictionary:dic];
                        [self->_dataSource1 addObject:model];
                    }
                self->_dataSource = [self->_dataSource1 mutableCopy];
                }if (arr.count==0||arr.count<10){
                    dispatch_async(dispatch_get_main_queue(), ^{
                        int tabviewTag = _currentPage % 2;
                        UITableView *reuseTableView = _scrollTableViews[tabviewTag];
                        [reuseTableView reloadData];
                        [self.myTableView1.mj_footer endRefreshing];
                        [self.myTableView2.mj_footer endRefreshing];
                        self.myTableView1.mj_footer.hidden = YES;
                        self.myTableView2.mj_footer.hidden = YES;

                        [self->_myTableView1.mj_footer setState:MJRefreshStateNoMoreData];
                        [self->_myTableView2.mj_footer setState:MJRefreshStateNoMoreData];
                    });
                    
                }
                NSLog(@"_dataSource1==%@",self->_dataSource1);

                break;
            case 1:
                //已接单
                NSLog(@"_dataSource2==%@",self->_dataSource2);
                NSLog(@"_dataSource1==%@",self->_dataSource1);

                if (arr&&![arr isEqual:[NSNull null]]) {
                    for (NSDictionary * dic in arr) {
                        woderenwuModel * model = [woderenwuModel new];
                        [model setValuesForKeysWithDictionary:dic];
                        [self->_dataSource2 addObject:model];
                    }
                    self->_dataSource = [self->_dataSource2 mutableCopy];
                }if (arr.count==0||arr.count<10){
                    dispatch_async(dispatch_get_main_queue(), ^{
                        int tabviewTag = _currentPage % 2;
                        UITableView *reuseTableView = _scrollTableViews[tabviewTag];
                        [reuseTableView reloadData];
                        [self.myTableView1.mj_footer endRefreshing];
                        [self.myTableView2.mj_footer endRefreshing];
                        self.myTableView1.mj_footer.hidden = YES;
                        self.myTableView2.mj_footer.hidden = YES;
                        
                        [self->_myTableView1.mj_footer setState:MJRefreshStateNoMoreData];
                        [self->_myTableView2.mj_footer setState:MJRefreshStateNoMoreData];
                    });
                    
                }
                
                break;
            case 2:
                //已接单
                if (arr&&![arr isEqual:[NSNull null]]) {
                    for (NSDictionary * dic in arr) {
                        woderenwuModel * model = [woderenwuModel new];
                        [model setValuesForKeysWithDictionary:dic];
                        [self->_dataSource3 addObject:model];
                    }
                    self->_dataSource = [self->_dataSource3 mutableCopy];
                }if (arr.count==0||arr.count<10){
                    dispatch_async(dispatch_get_main_queue(), ^{
                        int tabviewTag = _currentPage % 2;
                        UITableView *reuseTableView = _scrollTableViews[tabviewTag];
                        [reuseTableView reloadData];
                        [self.myTableView1.mj_footer endRefreshing];
                        [self.myTableView2.mj_footer endRefreshing];
                        self.myTableView1.mj_footer.hidden = YES;
                        self.myTableView2.mj_footer.hidden = YES;
                        
                        [self->_myTableView1.mj_footer setState:MJRefreshStateNoMoreData];
                        [self->_myTableView2.mj_footer setState:MJRefreshStateNoMoreData];
                    });
                    
                }
                break;
            case 3:
                //已接单
                if (arr&&![arr isEqual:[NSNull null]]) {
                    for (NSDictionary * dic in arr) {
                        woderenwuModel * model = [woderenwuModel new];
                        [model setValuesForKeysWithDictionary:dic];
                        [self->_dataSource4 addObject:model];
                    }
                    self->_dataSource = [self->_dataSource4 mutableCopy];
                }if (arr.count==0||arr.count<10){
                    dispatch_async(dispatch_get_main_queue(), ^{
                        int tabviewTag = _currentPage % 2;
                        UITableView *reuseTableView = _scrollTableViews[tabviewTag];
                        [reuseTableView reloadData];
                        [self.myTableView1.mj_footer endRefreshing];
                        [self.myTableView2.mj_footer endRefreshing];
                        self.myTableView1.mj_footer.hidden = YES;
                        self.myTableView2.mj_footer.hidden = YES;
                        
                        [self->_myTableView1.mj_footer setState:MJRefreshStateNoMoreData];
                        [self->_myTableView2.mj_footer setState:MJRefreshStateNoMoreData];
                    });
                    
                }
                
                break;
            case 4:
                //已接单
                if (arr&&![arr isEqual:[NSNull null]]) {
                    for (NSDictionary * dic in arr) {
                        woderenwuModel * model = [woderenwuModel new];
                        [model setValuesForKeysWithDictionary:dic];
                        [self->_dataSource5 addObject:model];
                    }
                    self->_dataSource = [self->_dataSource5 mutableCopy];
                }if (arr.count==0||arr.count<10){
                    dispatch_async(dispatch_get_main_queue(), ^{
                        int tabviewTag = _currentPage % 2;
                        UITableView *reuseTableView = _scrollTableViews[tabviewTag];
                        [reuseTableView reloadData];
                        [self.myTableView1.mj_footer endRefreshing];
                        [self.myTableView2.mj_footer endRefreshing];
                        self.myTableView1.mj_footer.hidden = YES;
                        self.myTableView2.mj_footer.hidden = YES;
                        
                        [self->_myTableView1.mj_footer setState:MJRefreshStateNoMoreData];
                        [self->_myTableView2.mj_footer setState:MJRefreshStateNoMoreData];
                    });
                    
                }
                
                break;
            case 5:
                //已接单
                if (arr&&![arr isEqual:[NSNull null]]) {
                    for (NSDictionary * dic in arr) {
                        woderenwuModel * model = [woderenwuModel new];
                        [model setValuesForKeysWithDictionary:dic];
                        [self->_dataSource6 addObject:model];
                    }
                    self->_dataSource = [self->_dataSource6 mutableCopy];
                }if (arr.count==0||arr.count<10){
                    dispatch_async(dispatch_get_main_queue(), ^{
                        int tabviewTag = _currentPage % 2;
                        UITableView *reuseTableView = _scrollTableViews[tabviewTag];
                        [reuseTableView reloadData];
                        [self.myTableView1.mj_footer endRefreshing];
                        [self.myTableView2.mj_footer endRefreshing];
                        self.myTableView1.mj_footer.hidden = YES;
                        self.myTableView2.mj_footer.hidden = YES;
                        
                        [self->_myTableView1.mj_footer setState:MJRefreshStateNoMoreData];
                        [self->_myTableView2.mj_footer setState:MJRefreshStateNoMoreData];
                    });
                    
                }
                break;
            default:
                break;
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            int tabviewTag = _currentPage % 2;
            UITableView *reuseTableView = _scrollTableViews[tabviewTag];
            [reuseTableView reloadData];
            [self.myTableView1.mj_footer endRefreshing];
            [self.myTableView2.mj_footer endRefreshing];
        });
        //        NSLog(@"arr=%@",arr);
        //        NSLog(@"_dataSource=%@",self->_dataSource);
        
    } failure:^(NSError *error) {
        
    }];
}
-(void)loadData{
    _pageNo1 =_pageNo2 =_pageNo3 =_pageNo4 =_pageNo5 =_pageNo6 = 1;
    if (!_dataSource) {
        _dataSource =[[NSMutableArray alloc]init];
    }
    if (!_temdataSource) {
        _temdataSource =[[NSMutableArray alloc]init];
    }
    if (!_dataSource1) {
        _dataSource =[[NSMutableArray alloc]init];
    }
    if (!_dataSource2) {
        _dataSource2 =[[NSMutableArray alloc]init];
    }
    if (!_dataSource3) {
        _dataSource3 =[[NSMutableArray alloc]init];
    }
    if (!_dataSource4) {
        _dataSource4 =[[NSMutableArray alloc]init];
    }if (!_dataSource5) {
        _dataSource5 =[[NSMutableArray alloc]init];
    }if (!_dataSource6) {
        _dataSource6 =[[NSMutableArray alloc]init];
    }
    self.myTableView1.mj_footer.hidden = NO;
    self.myTableView2.mj_footer.hidden = NO;
    NSMutableDictionary *dic =[NSMutableDictionary dictionary];
    switch (_currentPage) {
        case 0:
            //已接单
            [dic setValue:@2 forKey:@"status"];
            _nameStr =@"已接单";

            break;
        case 1:
            //已接单
            [dic setValue:@3 forKey:@"status"];
            _nameStr =@"已完工";
            break;
        case 2:
            //已接单
            [dic setValue:@4 forKey:@"status"];
            _nameStr =@"已审核";
            break;
        case 3:
            //已接单
            [dic setValue:@5 forKey:@"status"];
            _nameStr =@"未通过";
            break;
        case 4:
            //已接单
            [dic setValue:@6 forKey:@"status"];
            _nameStr =@"已付款";
            break;
        case 5:
            //已接单
//            [dic setValue:@2 forKey:@"status"];
            _nameStr =@"全部";
            break;
        default:
            break;
    }
    [dic setValue:@10 forKey:@"size"];
    [dic setValue:@1 forKey:@"page"];
    [dic setValue:my_AppDelegate.token forKey:@"token"];
    self.myTableView1.scrollEnabled = NO;
    self.myTableView2.scrollEnabled = NO;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.myTableView1.scrollEnabled = YES;
        self.myTableView2.scrollEnabled = YES;
    });
    [_dataSource removeAllObjects];
    int tabviewTag = _currentPage % 2;
    UITableView *reuseTableView = _scrollTableViews[tabviewTag];
    [reuseTableView reloadData];
    [NetWorking startPOSTRequestWithUrl:@"ordergetDoctorOrder" parameters:dic logMes:_nameStr show:NO success:^(NSDictionary *data) {
        self.myTableView1.scrollEnabled = YES;
        self.myTableView2.scrollEnabled = YES;
        NSArray *arr = [data objectForKey:@"data"];
        self->_sum = [data objectForKey:@"sum"];
        if ([arr isEqual:[NSNull null]]) {
            self->_myImageView.hidden = YES;
            [self.myTableView1.mj_header endRefreshing];
            [self.myTableView2.mj_header endRefreshing];
            return ;
        }
        if (arr.count == 0||!arr) {
            self->_myImageView.hidden = NO;
        }else{
            self->_myImageView.hidden = YES;

        }
        if (arr.count==0||arr.count<10||!arr){
            dispatch_async(dispatch_get_main_queue(), ^{
                int tabviewTag = self->_currentPage % 2;
                UITableView *reuseTableView = self->_scrollTableViews[tabviewTag];
                [reuseTableView reloadData];
                [self.myTableView1.mj_footer endRefreshing];
                [self.myTableView2.mj_footer endRefreshing];
                self.myTableView1.mj_footer.hidden = YES;
                self.myTableView2.mj_footer.hidden = YES;
                
                [self->_myTableView1.mj_footer setState:MJRefreshStateNoMoreData];
                [self->_myTableView2.mj_footer setState:MJRefreshStateNoMoreData];
            });
        }
        switch (self->_currentPage) {
            case 0:
                //已接单
                [self->_dataSource1 removeAllObjects];
                self->_dataSource1 = [woderenwuModel modelSformDics:arr];
                self->_dataSource = [self->_dataSource1 mutableCopy];
                
                break;
            case 1:
                //已接单
                [self->_dataSource2 removeAllObjects];
                self->_dataSource2 = [woderenwuModel modelSformDics:arr];
                self->_dataSource = [self->_dataSource2 mutableCopy];

                break;
            case 2:
                //已接单
                [self->_dataSource3 removeAllObjects];
                self->_dataSource3 = [woderenwuModel modelSformDics:arr];
                self->_dataSource = [self->_dataSource3 mutableCopy];
                break;
            case 3:
                //已接单
                [self->_dataSource4 removeAllObjects];
                self->_dataSource4 = [woderenwuModel modelSformDics:arr];
                self->_dataSource = [self->_dataSource4 mutableCopy];

                break;
            case 4:
                //已接单
                [self->_dataSource5 removeAllObjects];
                self->_dataSource5 = [woderenwuModel modelSformDics:arr];
                self->_dataSource = [self->_dataSource5 mutableCopy];

                break;
            case 5:
                //已接单
                [self->_dataSource6 removeAllObjects];
                self->_dataSource6 = [woderenwuModel modelSformDics:arr];
                self->_dataSource = [self->_dataSource6 mutableCopy];
                break;
            default:
                break;
        }
        int tabviewTag = _currentPage % 2;
        UITableView *reuseTableView = _scrollTableViews[tabviewTag];
        [reuseTableView reloadData];
        [self.myTableView1.mj_header endRefreshing];
        [self.myTableView2.mj_header endRefreshing];

    } failure:^(NSError *error) {
        
    }];
}
-(void)loadData4{
    _dateSearch = NO;
    _pageNo1 =_pageNo2 =_pageNo3 =_pageNo4 =_pageNo5 =_pageNo6 = 1;
    if (!_dataSource) {
        _dataSource =[[NSMutableArray alloc]init];
    }
    if (!_temdataSource) {
        _temdataSource =[[NSMutableArray alloc]init];
    }
    if (!_dataSource1) {
        _dataSource =[[NSMutableArray alloc]init];
    }
    if (!_dataSource2) {
        _dataSource2 =[[NSMutableArray alloc]init];
    }
    if (!_dataSource3) {
        _dataSource3 =[[NSMutableArray alloc]init];
    }
    if (!_dataSource4) {
        _dataSource4 =[[NSMutableArray alloc]init];
    }if (!_dataSource5) {
        _dataSource5 =[[NSMutableArray alloc]init];
    }if (!_dataSource6) {
        _dataSource6 =[[NSMutableArray alloc]init];
    }
    self.myTableView1.mj_footer.hidden = NO;
    self.myTableView2.mj_footer.hidden = NO;
    NSMutableDictionary *dic =[NSMutableDictionary dictionary];
    switch (_currentPage) {
        case 0:
            //已接单
            [dic setValue:@2 forKey:@"status"];
            _nameStr =@"已接单";
            
            break;
        case 1:
            //已接单
            [dic setValue:@3 forKey:@"status"];
            _nameStr =@"已完工";
            break;
        case 2:
            //已接单
            [dic setValue:@4 forKey:@"status"];
            _nameStr =@"已审核";
            break;
        case 3:
            //已接单
            [dic setValue:@5 forKey:@"status"];
            _nameStr =@"未通过";
            break;
        case 4:
            //已接单
            [dic setValue:@6 forKey:@"status"];
            _nameStr =@"已付款";
            break;
        case 5:
            //已接单
            //            [dic setValue:@2 forKey:@"status"];
            _nameStr =@"全部";
            break;
        default:
            break;
    }
    [dic setValue:@1000 forKey:@"size"];
    [dic setValue:_startStr forKey:@"startDate"];
    [dic setValue:_endStr forKey:@"endDate"];
    [dic setValue:@1 forKey:@"page"];
    [dic setValue:my_AppDelegate.token forKey:@"token"];
    self.myTableView1.scrollEnabled = NO;
    self.myTableView2.scrollEnabled = NO;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(10 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.myTableView1.scrollEnabled = YES;
        self.myTableView2.scrollEnabled = YES;
    });
    [_dataSource removeAllObjects];
    int tabviewTag = _currentPage % 2;
    UITableView *reuseTableView = _scrollTableViews[tabviewTag];
    [reuseTableView reloadData];
    [NetWorking startPOSTRequestWithUrl:@"ordergetDoctorOrder" parameters:dic logMes:_nameStr show:NO success:^(NSDictionary *data) {
        self.myTableView1.scrollEnabled = YES;
        self.myTableView2.scrollEnabled = YES;
        NSArray *arr = [data objectForKey:@"data"];
        self->_sum = [data objectForKey:@"sum"];
        if ([arr isEqual:[NSNull null]]) {
            self->_myImageView.hidden = YES;
            [self.myTableView1.mj_header endRefreshing];
            [self.myTableView2.mj_header endRefreshing];
            return ;
        }
        if (arr.count == 0||!arr) {
            self->_myImageView.hidden = NO;
        }else{
            self->_myImageView.hidden = YES;
            
        }
        if (arr.count==0||arr.count<10||!arr){
            dispatch_async(dispatch_get_main_queue(), ^{
                int tabviewTag = _currentPage % 2;
                UITableView *reuseTableView = _scrollTableViews[tabviewTag];
                [reuseTableView reloadData];
                [self.myTableView1.mj_footer endRefreshing];
                [self.myTableView2.mj_footer endRefreshing];
                self.myTableView1.mj_footer.hidden = YES;
                self.myTableView2.mj_footer.hidden = YES;
                
                [self->_myTableView1.mj_footer setState:MJRefreshStateNoMoreData];
                [self->_myTableView2.mj_footer setState:MJRefreshStateNoMoreData];
            });
        }
        switch (self->_currentPage) {
            case 0:
                //已接单
                [self->_dataSource1 removeAllObjects];
                self->_dataSource1 = [woderenwuModel modelSformDics:arr];
                self->_dataSource = [self->_dataSource1 mutableCopy];
                
                break;
            case 1:
                //已接单
                [self->_dataSource2 removeAllObjects];
                self->_dataSource2 = [woderenwuModel modelSformDics:arr];
                self->_dataSource = [self->_dataSource2 mutableCopy];
                
                break;
            case 2:
                //已接单
                [self->_dataSource3 removeAllObjects];
                self->_dataSource3 = [woderenwuModel modelSformDics:arr];
                self->_dataSource = [self->_dataSource3 mutableCopy];
                break;
            case 3:
                //已接单
                [self->_dataSource4 removeAllObjects];
                self->_dataSource4 = [woderenwuModel modelSformDics:arr];
                self->_dataSource = [self->_dataSource4 mutableCopy];
                
                break;
            case 4:
                //已接单
                [self->_dataSource5 removeAllObjects];
                self->_dataSource5 = [woderenwuModel modelSformDics:arr];
                self->_dataSource = [self->_dataSource5 mutableCopy];
                
                break;
            case 5:
                //已接单
                [self->_dataSource6 removeAllObjects];
                self->_dataSource6 = [woderenwuModel modelSformDics:arr];
                self->_dataSource = [self->_dataSource6 mutableCopy];
                break;
            default:
                break;
        }
        int tabviewTag = _currentPage % 2;
        UITableView *reuseTableView = _scrollTableViews[tabviewTag];
        [reuseTableView reloadData];
        [self.myTableView1.mj_header endRefreshing];
        [self.myTableView2.mj_header endRefreshing];
        
    } failure:^(NSError *error) {
        
    }];
}
-(void)changeData{
    
    switch (_currentPage) {
        case 0:
            //已接单
            _nameStr =@"已接单";
            if (!_dataSource1.count) {
                [self loadData];
            }else{
                [self changeSouce];
            }
            break;
        case 1:
            //已接单
            if (_dataSource2.count==0||!_dataSource2) {
                [self loadData];
            }else{
                [self changeSouce];
            }
            _nameStr =@"已完工";
            break;
        case 2:
            //已接单
            if (!_dataSource3.count) {
                [self loadData];
            }else{
                [self changeSouce];
            }
            _nameStr =@"已审核";
            break;
        case 3:
            //已接单
            if (!_dataSource4.count) {
                [self loadData];
            }else{
                [self changeSouce];
            }
            _nameStr =@"未通过";
            break;
        case 4:
            //已接单
            if (!_dataSource5.count) {
                [self loadData];
            }else{
                [self changeSouce];
            }
            _nameStr =@"已付款";
            break;
        case 5:
            //已接单
            if (!_dataSource6.count) {
                [self loadData];
            }else{
                [self changeSouce];
            }
            _nameStr =@"全部";
            break;
        default:
            break;
    }
   
    
        //        NSLog(@"arr=%@",arr);
        //        NSLog(@"_dataSource=%@",self->_dataSource);
        
}
-(void)changeSouce{
    _myImageView.hidden = YES;

    switch (_currentPage) {
        case 0:
            //已接单
            self->_dataSource = [self->_dataSource1 mutableCopy];
            
            break;
        case 1:
            //已接单
            self->_dataSource = [self->_dataSource2 mutableCopy];;
            
            break;
        case 2:
            //已接单
            self->_dataSource = [self->_dataSource3 mutableCopy];
            break;
        case 3:
            //已接单
            self->_dataSource = [self->_dataSource4 mutableCopy];
            
            break;
        case 4:
            //已接单
            self->_dataSource = [self->_dataSource5 mutableCopy];
            
            break;
        case 5:
            //已接单
            self->_dataSource = [self->_dataSource6 mutableCopy];
            break;
        default:
            break;
    }
    [self.myTableView1 reloadData];
    [self.myTableView2 reloadData];
    [self.myTableView1.mj_header endRefreshing];
    [self.myTableView2.mj_header endRefreshing];
}
#pragma mark --rightBtn--
-(void)creatNavRightBtn{
    UIBarButtonItem *pulishButton = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:@selector(search)];
    [pulishButton setTintColor:[UIColor whiteColor]];
    UIBarButtonItem * saveButton= [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"riqi_bai"] style:UIBarButtonItemStylePlain target:self action:@selector(save)];
    [saveButton setTintColor:[UIColor whiteColor]];

    [self.navigationItem setRightBarButtonItems:[NSArray arrayWithObjects:saveButton,pulishButton,nil]];
}
-(void)search{
    searchController * vc = [searchController new];
//    vc.dataSource = _dataSource;
    vc.sum = _sum;
    vc.currentPage = _currentPage;
    vc.title = @"查找";
    [self.navigationController pushViewController:vc animated:YES];
}
- (void)save{
    RangePickerViewController *vc = [[RangePickerViewController alloc] init];
    __weak typeof(self) weakSelf = self;
    [vc setSelectCheckDateBlock:^(NSString *startDateStr, NSString *endDateStr) {
        weakSelf.startDateLabel.text = startDateStr;
        weakSelf.endDateLabel.text = endDateStr;
        NSLog(@"%.0ld\n%.0ld",(long)[startDateStr integerValue], (long)[endDateStr integerValue]);
        if (!endDateStr) {
//            endDateStr = [NSString stringWithFormat:@"%.0ld",[startDateStr integerValue]+86399000];
            endDateStr = startDateStr;
            self->_startStr = startDateStr;
            self->_endStr = endDateStr;
        }else{
            if ((long)[startDateStr integerValue]>(long)[endDateStr integerValue]) {
//                startDateStr = [NSString stringWithFormat:@"%.0ld",[startDateStr integerValue]+86399000];
                self->_startStr = endDateStr;
                self->_endStr = startDateStr;
            }else{
//                endDateStr = [NSString stringWithFormat:@"%.0ld",[endDateStr integerValue]+86399000];
                self->_endStr = endDateStr;
                self->_startStr = startDateStr;
            }
        }
        NSLog(@"%@\n%@", [ZXToolObj getTimeStringFormtimestamp:self->_startStr], [ZXToolObj getTimeStringFormtimestamp:_endStr]);
        [self loadData4];
        
    }];
    [self presentViewController:vc animated:YES completion:^{
        self->_dateSearch = YES;
    }];
//    [self.navigationController pushViewController:vc animated:YES];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
    // Dispose of any resources that can be recreated.
}


@end
